package com.bosssoft.user.permission.center.serve.util;

import com.bosssoft.user.permission.center.serve.pojo.dto.LoginDTO;
import com.bosssoft.user.permission.center.serve.pojo.dto.LoginRoleDTO;
import com.bosssoft.user.permission.center.serve.pojo.vo.LoginVO;
import common.core.JwtPayloadHolder;
import common.exception.code.BizErrorCode;
import common.exception.parse.BusinessException;
import common.util.JwtUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: LoginVOTokenUtil
 * @description: 用于登录信息token的生成
 * @author: lanyukai
 * @date: 2024/6/12 17:08
 * @since 1.0
 **/
public class LoginTokenUtil {
    /**
     * 根据用户id生成token
     * @param loginVO 登录vo信息
     * @return token信息
     */
    public static String generateTokenByLoginDTO(LoginVO loginVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", loginVO);
        return JwtUtil.generateToken(map);
    }
    /**
     * 将token内容解析为LoginDTO
     * @author lanyukai
     * @date 2024/06/15 13:15
     * @return 用户信息的DTO
     */
    public static LoginDTO parseTokenToLoginDTO() {
        Object object = JwtPayloadHolder.getPayload().get("token");
        if (object instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) object;
            LoginDTO loginDTO = new LoginDTO();
            // 可在此修改其它属性
            loginDTO.setId(Long.parseLong(map.get("id").toString()));
            loginDTO.setName((String)map.get("name"));
            loginDTO.setCode((String)map.get("code"));
            loginDTO.setTenantId(Long.parseLong(map.get("tenantId").toString()));
            loginDTO.setOrgId(Long.parseLong(map.get("orgId").toString()));
            loginDTO.setCompanyId(Long.parseLong(map.get("companyId").toString()));
            // 解析角色列表
            loginDTO.setRoleList(getRoleListFromToken((List<Map<String, Object>>) map.get("roleList")));
            return loginDTO;
        } else {
            throw new BusinessException(BizErrorCode.UNDEFINED, "解析出了未定义的token");
        }
    }
    /**
     * 将token中的角色列表解析出来
     * @author lanyukai
     * @date 2024/06/15 14:39
     * @param objectList 通过map.get解析出的list
     * @return 解析完的角色列表信息
     */
    private static List<LoginRoleDTO> getRoleListFromToken(List<Map<String, Object>> objectList){
        List<LoginRoleDTO> loginRoleDTOS = new ArrayList<>();
        for(Map<String, Object> map : objectList){
            // 可在此修改其它属性
            LoginRoleDTO loginRoleDTO = new LoginRoleDTO();
            loginRoleDTO.setId(Long.parseLong(map.get("id").toString()));
            loginRoleDTO.setName((String)map.get("name"));
            loginRoleDTOS.add(loginRoleDTO);
        }
        return loginRoleDTOS;
    }
}
